<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>欢迎页面-X-admin2.2</title>
  <meta th:include="~{layout/head_xadmin :: content}">
</head>
<body style="background-color: white;padding: 10px 10px;">
<div id="tree-role"></div>
<button class="layui-btn layui-btn-normal" onclick="save()" style="margin-top: 20%;">保存</button>
</body>

<script>
  var tree, userId = [[${userId}]]
  layui.use(['tree', 'layer', 'jquery'], function () {
    tree = layui.tree;
    var layer = layui.layer;
    var $ = layui.jquery;

    $(function () {
      $.ajax({
        data: {'userId': userId},
        url: '/admin/permission/roleList',
        success: function (data) {
          let treeData = data.data
          //渲染
          var inst1 = tree.render({
            elem: '#tree-role'  //绑定元素
            , id: 'treeId'
            , data: treeData
            , checkChirld: false //是否关联子集菜单---修改了tree源码
            , showLine: false
            , showCheckbox: true  //是否显示复选框
            , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
            , click: function (obj) {
            }
          });
        }
      })
    })
  });

  function save() {
    let checkData = tree.getChecked('treeId');
    ids = []
    for (let i = 0; i < checkData.length; i++) {
      ids.push(checkData[i].id)
    }
    //取出菜单id
    $.ajax({
      data: {'userId': userId, 'ids': (ids.length == 0 ? '' : ids.toString())},
      url: '/admin/permission/updateUserRole',
      type: 'post',
      success: function (data) {
        layer.msg(data.message)
        if (data.code == 0) {
          var index = window.parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
          window.setTimeout(function () {
            window.parent.layer.close(index); //再执行关闭
          }, 1200)
        }
      }
    })
  }

  function listToTree(list, pid) {
    let tree = []
    for (let i = 0; i < list.length; i++) {
      let temp = list[i]
      if (temp.pid == pid) {
        //递归子节点
        temp.children = listToTree(list, temp.id);
        tree.push(temp)
      }
    }
    return tree;
  }

  function treeTolist(tree) {
    let list = []
    for (let i = 0; i < tree.length; i++) {
      list.push(tree[i].id)
      if (tree[i].children.length != 0) {
        //递归
        let temp = treeTolist(tree[i].children)
        //数组合并
        for (let j = 0; j < temp.length; j++) {
          list.push(temp[j]);
        }
      }
    }
    return list
  }
</script>
</html>
